<template>
  <div class="secure-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="安全中心" left-text="返回" fixed left-arrow @click-left="$router.back()" />
    <div class="bg"></div>
    <!-- 修改密码和注销账号 -->
    <div class="user-option">
      <van-cell title="修改密码" is-link @click="show = true" />
      <van-popup v-model="show" position="bottom" closeable :style="{ 'min-height': '30%' }">
        <div class="update-pwd">
          <div class="title">修改密码</div>
          <!-- 旧密码 -->
          <!-- 通过 validator 进行函数校验 -->
          <van-form>
            <van-field
              v-model.trim="oldPwd"
              :type="text"
              label="旧密码"
              name="validator"
              placeholder="输入密码"
              :right-icon="eye"
              @click-right-icon="toggleEye"
              :rules="[
                { required: true, message: '密码必填' },
                { validator, message: '密码长度位6-16位数字字母组合' }
              ]"
            />
            <!-- 新密码 -->
            <!-- 通过 validator 进行函数校验 -->
            <van-field
              v-model.trim="newPwd"
              :type="text"
              label="新密码"
              name="validator"
              placeholder="输入密码"
              :right-icon="eye"
              @click-right-icon="toggleEye"
              :rules="[
                { required: true, message: '密码必填' },
                { validator, message: '密码长度位6-16位数字字母组合' }
              ]"
            />
            <div class="login-btn">
              <van-button round block type="info" @click="updatePwd">确认修改</van-button>
            </div>
          </van-form>
        </div>
      </van-popup>
      <van-cell title="注销账号" is-link @click="cancellationAccount" />
    </div>
    <div class="login-btn">
      <van-button round block type="info" @click="exitLogin">退出登录</van-button>
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'secure-com',
  data() {
    return {
      show: false,
      eye: 'closed-eye',
      text: 'password',
      oldPwd: '',
      newPwd: ''
    }
  },
  methods: {
    toggleEye() {
      if (this.eye === 'closed-eye') {
        this.eye = 'eye-o'
        this.text = 'text'
      } else {
        this.eye = 'closed-eye'
        this.text = 'password'
      }
    },
    // 对表单数据进行验证
    validator(val) {
      return /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,16}$/.test(val)
    },
    // 修改密码
    async updatePwd() {
      if (this.oldPwd === this.newPwd) {
        return Notify({ type: 'danger', message: '新密码不能和旧密码相同' })
      }
      this.$toast.loading({
        message: '加载中...',
        duration: 0
      })
      try {
        // 发起请求修改密码
        const data = await axios.post('/user/update/password', {
          password: this.oldPwd,
          newPassword: this.newPwd
        })
        if (data.code === 0) {
          Notify({
            type: 'success',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              // 删除本地token
              localStorage.removeItem('user_token')
              // 跳转到登录页面
              this.$router.replace('/login')
            }
          })
        } else if (data.msg === '身份认证错误' || data.code === 403) {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              // 删除本地token
              localStorage.removeItem('user_token')
              // 跳转到登录页面
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({ type: 'danger', message: data.msg, duration: 1000 })
        }
      } catch {
        Notify({ type: 'danger', message: '请求失败！', duration: 1000 })
      } finally {
        this.$toast.clear()
      }
    },
    // 退出登录
    async exitLogin() {
      this.$dialog
        .confirm({
          title: '退出登录',
          message: '确定要退出登录吗？'
        })
        .then(async () => {
          this.$toast.loading({
            duration: 0,
            message: '加载中...'
          })
          try {
            const data = await axios.post('/user/logout')
            if (data.code === 0) {
              Notify({
                type: 'success',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  // 删除本地token
                  localStorage.removeItem('user_token')
                  // 跳转到登录页面
                  this.$router.replace('/login')
                }
              })
            } else if (data.msg === '身份认证错误' || data.code === 403) {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  // 删除本地token
                  localStorage.removeItem('user_token')
                  // 跳转到登录页面
                  this.$router.replace('/login')
                }
              })
            } else {
              Notify({ type: 'danger', message: data.msg, duration: 1000 })
            }
          } catch {
            Notify({ type: 'danger', message: '请求失败！', duration: 1000 })
          } finally {
            this.$toast.clear()
          }
        })
        .catch(() => {
          return
        })
    },
    // 注销账号
    async cancellationAccount() {
      this.$dialog
        .confirm({
          title: '注销账号',
          message: '是否确认注销账号,一旦确认无法恢复'
        })
        .then(async () => {
          this.$toast.loading({
            duration: 0,
            message: '加载中...'
          })
          try {
            const data = await axios.post('/user/cancellation')
            if (data.code === 0) {
              Notify({
                type: 'success',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  // 删除本地token
                  localStorage.removeItem('user_token')
                  // 跳转到登录页面
                  this.$router.replace('/login')
                }
              })
            } else if (data.msg === '身份认证错误' || data.code === 403) {
              Notify({
                type: 'danger',
                message: data.msg,
                duration: 1000,
                onClose: () => {
                  // 删除本地token
                  localStorage.removeItem('user_token')
                  // 跳转到登录页面
                  this.$router.replace('/login')
                }
              })
            } else {
              Notify({ type: 'danger', message: data.msg, duration: 1000 })
            }
          } catch {
            Notify({ type: 'danger', message: '请求失败！', duration: 1000 })
          } finally {
            this.$toast.clear()
          }
        })
        .catch(() => {
          return
        })
    }
  }
}
</script>

<style lang="less" scoped>
.secure-container {
  background-color: #f5f5f5;
  padding-top: 46px;
  height: 100vh;
  box-sizing: border-box;

  .bg {
    height: 100px;
    background-color: #f92946;
  }
  .user-option {
    margin: -30px 10px 0;
    padding: 10px;
    background-color: white;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;

    .update-pwd {
      padding: 20px;

      .title {
        margin-bottom: 20px;
        color: #444;
        font-size: 18px;
        line-height: 24px;
      }

      .login-btn {
        margin-top: 40px !important;
      }
    }
  }
  ::v-deep .van-field--error .van-field__control,
  ::v-deep .van-field--error .van-field__control::placeholder {
    color: rgba(50, 50, 50, 0.5);
    -webkit-text-fill-color: currentColor;
  }

  .login-btn {
    margin-top: 100px;
    padding: 10px;

    .van-button--info {
      background-color: #f92946;
      border-color: #f92946;
    }

    .register-btn {
      background-color: #fff;
      color: rgb(50, 50, 51);
      border: 1px solid rgb(235, 237, 240);
    }
  }
  ::v-deep .van-nav-bar__text,
  ::v-deep .van-nav-bar .van-icon {
    color: #323232;
  }
}
</style>
